<script lang='ts' setup>
import { onMounted, ref, watch } from 'vue';
import { Plus, Search, Refresh, Loading, SuccessFilled, ArrowDown } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import EditMenuDialog from "@/components/EditMenuDialog.vue";
import EditModuleDialog from "@/components/EditModuleDialog.vue";
import router from '@/router';
import { getAppList, addApp, type AppInterface, appDetail, deleteApp, updateApp, exportSql } from '@/api/appManage';
import type { PageInterface } from '@/api/common';
import { getMenuList, type MenuInterface } from '@/api/menuManage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserList, UserInterface } from '@/api/userManage';
import ImageUpload from "@/components/ImageUpload/index.vue";
const rules = {
  name: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { max: 64, message: '最长64个字符', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 64, message: '最长64个字符', trigger: 'blur' }
  ]

}
const route = useRoute();

const formData = ref<AppInterface>({
  id: '',
  userName: '',
  name: '',
  enterAppBeforeLogin: 1,
  createBy: null,
  updateBy: null,
  createTime: '',
  updateTime: '',
  delFlag: '',
  backgroundUrl: '',
  remarks: null,
})
const queryForm = ref<AppInterface>({
  name: '',
  userName: '',
  enterAppBeforeLogin: 1,
})
const pagination = ref<PageInterface>({
  page: 1,
  limit: 10,
})
const totalCount = ref(0)
const list = ref<Array<AppInterface>>([])
const currentAppId = ref('')

/**
 * 显示编辑菜单弹窗
 *
 * 打开菜单对话框，使用户能够编辑菜单内容。
 */
function handleEditMenu(appId: string) {
  menuDialogVisible.value = true
  currentAppId.value = appId
  // menuTreeData.value = JSON.parse(localStorage.getItem("menuTreeData") as string) || [];
}

//菜单树结构数据 
const menuTreeData = ref<MenuInterface[]>([]);

// 接收菜单组件传来的数据，并更新菜单树结构数据
function changeMenuData(treeData: MenuInterface[]) {
  menuTreeData.value = treeData;
  //将编辑的菜单数据保存到本地存储中
}

const menuDialogVisible = ref(false);
const currentPageMenuItem = ref<MenuInterface>({} as MenuInterface);

/**
 * 选择编辑页面
 *
 * @param menuItem 树形结构的菜单项
 */
function selectEditPage(menuItem: MenuInterface) {
  currentPageMenuItem.value = menuItem;
  router.push({ path: '/editor', query: { menuId: menuItem.id, appId: menuItem.appId } });
}

//-----------模型相关-------------

const moduleTreeData = ref<any[]>([])
/**
 * 编辑模型
 *
 * 该函数用于跳转到接口管理页面。
 */
const moduleDialogVisible = ref(false)

function editModule(appId: string) {
  moduleDialogVisible.value = true
  currentAppId.value = appId
}

//-----------模型相关结束-------------

function getList() {
  getAppList({ ...queryForm.value, ...pagination.value }).then((res: any) => {
    list.value = res.data.list
    totalCount.value = res.data.totalCount
    pagination.value.page = res.data.page
  })
}

const dialogVisible = ref(false)

function handleAdd() {
  dialogVisible.value = true
}

function addAppSuccess() {
  dialogVisible.value = false
  getList()
}

const formDataRef = ref()

function submit() {
  formDataRef.value.validate((valid: any) => {
    if (valid) {
      if (formData.value.id) {
        updateApp(formData.value).then((res: any) => {
          ElMessage.success('修改成功')
          close()
          getList()
        })
      } else {
        addApp(formData.value).then((res: any) => {
          ElMessage.success('添加成功')
          close()
          getList()
        })
      }
    }
  })
}

function handleEditApp(row: any) {
  console.log(row);

  formData.value = { ...row }
  dialogVisible.value = true

  // appDetail(id).then((res: any) => {
  //   formData.value = res.data
  //   dialogVisible.value = true
  // })
}

function close() {
  dialogVisible.value = false
  formData.value = {
    id: '',
    userName: '',
    name: '',
    enterAppBeforeLogin: 1,
    createBy: null,
    updateBy: null,
    createTime: '',
    updateTime: '',
    delFlag: '',
    remarks: null
  }
  formDataRef.value.clearValidate()
}

const queryFormRef = ref()

function reset() {
  queryFormRef.value.resetFields()
  getList()
}

function handleDeleteApp(id: string) {
  ElMessageBox.confirm('确定要删除该应用吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteApp(id).then((res: any) => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}

let allUserList = ref<Array<UserInterface>>()

/**
 * 获取所有用户列表
 *
 * @returns 返回所有用户信息的数组
 */
function getAllUser() {
  getUserList({ page: 1, limit: 10000000 }).then((res: any) => {
    allUserList.value = res.data.list;
  })
}

async function getDirectory() {
  // @ts-ignore
  // const handle = await showDirectoryPicker();
  // console.log(handle.name);

}
const buildPercentage = ref(90)
const showLog = ref(true)
const isBuilding = ref(false)
const buildDialogVisible = ref(false)
function buildMirror() {
  buildDialogVisible.value = true
  isBuilding.value = true
}
function closeBuildMirror() {
  buildDialogVisible.value = false
}
function buildSuccess() {
  isBuilding.value = false
}

const showBuildCreateTableScriptDialog = ref(false)
const createTableScript = ref('')
function exportAppSql(row: any) {
  exportSql(row.id).then((res: any) => {
    createTableScript.value = res.data
    showBuildCreateTableScriptDialog.value = true
  })
}

/**
 * 复制SQL语句到剪贴板
 */
function copySql() {
  navigator.clipboard.writeText(createTableScript.value)
  ElMessage({
    type: 'success',
    message: '复制成功！'
  })
  showBuildCreateTableScriptDialog.value = false
}


getList()
getAllUser()
onMounted(() => {
  // 从本地存储中获取菜单和页面数据
  let menuTree = localStorage.getItem("menuTreeData");
  menuTree = !menuTree ? [] : JSON.parse(menuTree);

  let moduleTree = localStorage.getItem("moduleTreeData");
  moduleTree = !moduleTree ? [] : JSON.parse(moduleTree);
  if (menuTree) {
    menuTreeData.value = menuTree as any;
    moduleTreeData.value = moduleTree as any
  }
});
watch(() => buildPercentage.value, () => {
  if (buildPercentage.value >= 100) {
    buildSuccess()
  }
}, { immediate: true })
</script>
<template>
  <div class="pageTitle">{{ route.meta.title }}</div>
  <el-form ref="queryFormRef" :model="queryForm" inline @submit.prevent>
    <el-form-item label="应用名：" prop="name">
      <el-input v-model="queryForm.name" clearable placeholder="应用名" @clear="getList" @keyup.enter="getList"></el-input>
    </el-form-item>
    <el-form-item label="用户：" prop="userName">
      <el-input v-model="queryForm.userName" clearable placeholder="用户名" @clear="getList"
        @keyup.enter="getList"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button :icon="Search" type="primary" @click="getList">查询</el-button>
      <el-button :icon="Refresh" type="primary" @click="reset">重置</el-button>
    </el-form-item>
  </el-form>
  <div class="tableOperBtns">
    <el-button :icon="Plus" type="primary" @click="handleAdd">新增</el-button>
  </div>
  <el-table :data="list" border class="table" empty-text="暂无数据" max-height="500px" style="width: 100%">
    <el-table-column label="序号" type="index" width="80"></el-table-column>
    <el-table-column label="应用名" prop="name"></el-table-column>
    <el-table-column label="应用id" prop="id"></el-table-column>
    <el-table-column label="登录背景" prop="backgroundUrl">
      <template #default="scope">
        <el-image v-if="scope.row.backgroundUrl" :src="scope.row.backgroundUrl" style="width: 100px; height: 100px;" />
        <div v-else>暂无背景图</div>
      </template>
    </el-table-column>
    <el-table-column label="用户名" prop="userName"></el-table-column>
    <el-table-column label="操作" prop="" width="600">
      <template #default="scope">
        <el-button text type="success" @click="handleEditMenu(scope.row.id)">编辑菜单</el-button>
        <el-button text type="warning" @click="editModule(scope.row.id)">编辑模型</el-button>
        <el-button text type="primary" @click="handleEditApp(scope.row)">编辑应用信息</el-button>
        <el-button text type="default" @click="exportAppSql(scope.row)">导出应用脚本</el-button>
        <!-- <el-button text type="" @click="buildMirror">{{ isBuilding && buildPercentage < 100 ? `镜像构建中1/4` : '构建镜像' }}
            <el-icon class="buildLoading" v-if="isBuilding && buildPercentage < 100" size="15">
            <Loading /></el-icon>
        </el-button> -->
        <el-button text type="danger" @click="handleDeleteApp(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="pagination.page" :total="totalCount" background class="pagePagination"
    layout="prev, pager, next" @change="getList" />
  <!-- 编辑菜单的弹窗 -->
  <edit-menu-dialog v-model:dialogVisible="menuDialogVisible" :appId="currentAppId" @selectEditPage="selectEditPage" />
  <!-- 编辑模型的弹窗 -->
  <edit-module-dialog v-model:dialogVisible="moduleDialogVisible" :appId="currentAppId" />
  <!-- 添加应用弹窗 -->
  <el-dialog v-model="dialogVisible" :title="formData.id?'编辑应用':'添加应用'" width="800px" @close="close">
    <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="160px" @submit.prevent>
      <el-form-item label="应用名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入应用名"></el-input>
      </el-form-item>
      <el-form-item label="用户" prop="userName">
        <el-select v-model="formData.userName" filterable placeholder="请选择用户">
          <el-option v-for="item in allUserList" :label="item.username" :value="item.username"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="登录前可进入网站" prop="enterAppBeforeLogin">
        <el-switch v-model="formData.enterAppBeforeLogin" active-value="2" inactive-value="1" active-text="是"
          inactive-text="否"></el-switch>
        <span>（仅网站应用有效）</span>
      </el-form-item>
      <el-form-item label="登录背景图" prop="backgroundUrl">
        <image-upload v-model="formData.backgroundUrl" :limit="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 构建镜像弹窗 -->
  <el-dialog v-model="buildDialogVisible" title="构建镜像" width="700px" @close="closeBuildMirror">
    <el-progress :percentage="buildPercentage" :stroke-width="20" :text-inside="true"
      :status="buildPercentage == 100 ? 'success' : ''">
      <span>1/4</span>
    </el-progress>
    <div class="buildText">
      <div class="buildTextLeft">
        <span>镜像构建{{ buildPercentage < 100 ? `中1/4` : '完成' }}</span>
            <el-icon class="buildLoading" v-if="buildPercentage < 100" size="15">
              <Loading />
            </el-icon>
            <el-icon style="margin-left: 5px;" color="#67c23a" v-if="buildPercentage >= 100" size="15">
              <SuccessFilled />
            </el-icon>
      </div>

      <el-button link type="primary" @click="showLog = !showLog">{{ showLog ? '收起' : '查看' }}日志
        <el-icon>
          <ArrowDown v-if="!showLog" />
          <ArrowUp v-else />
        </el-icon>
      </el-button>
    </div>
    <div v-show="showLog">
      <div class="logbox">
        <div>132</div>
      </div>
    </div>
    <el-button type="primary" @click="buildPercentage++">+</el-button>
  </el-dialog>
  <!-- 导出脚本的弹窗 -->
  <el-dialog title='创建表SQL' v-model='showBuildCreateTableScriptDialog' @close='showBuildCreateTableScriptDialog = false'
    width='1200px'>
    <div class="sqlCreateTable">
      <pre class="sqlCreateTable_preview">{{ createTableScript }}</pre>
      <div class="sqlCreateTable_footer" style="display: flex; justify-content: end;">
        <el-button type='success' icon="CopyDocument" @click='copySql'>复制</el-button>
        <el-button type='primary' @click='showBuildCreateTableScriptDialog = false'>关闭</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<style lang='scss' scoped>
.sqlCreateTable {

  &_preview {
    max-height: 80vh;
    background: black;
    margin: 0;
    overflow: auto;
    padding: 10px;
    color: white;

    &::-webkit-scrollbar {
      width: 12px;
      /* 垂直滚动条宽度 */
      height: 12px;
      /* 水平滚动条高度 */
    }

    &::-webkit-scrollbar-track {
      background: #3e3e3e;
      border-radius: 1px;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      border-radius: 1px;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #777777;
    }
  }

  &_footer {
    margin-top: 10px;
  }
}

.logbox {

  overflow: auto;
  max-width: 700px;
  max-height: 500px;

  div {
    white-space: nowrap;
  }
}

.buildLoading {
  margin-left: 5px;
  animation: loadingRotate 2s linear infinite;
}

.buildText {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;

  &Left {
    display: flex;
    align-items: center;
  }
}

@keyframes loadingRotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }

}
</style>